package com.lxy.auth.controller;


import cn.hutool.core.bean.BeanUtil;
import com.lxy.auth.constant.RoleConstant;
import com.lxy.auth.dto.LoginDto;
import com.lxy.auth.dto.UserDto;
import com.lxy.auth.service.UserService;
import com.lxy.common.constant.HttpStatus;
import com.lxy.common.domain.AjaxResult;
import com.lxy.common.group.V;
import com.lxy.token.TokenTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/api")
public class UserController {


    @Autowired
    UserService userService;

    @Autowired
    TokenTemplate tokenTemplate;

    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@Validated @RequestBody LoginDto loginDto, BindingResult result) {
        V.validate(result);
        //根据用户名查询
        UserDto user = userService.queryByAccount(loginDto.getUsername());
        if (null == user) {
            return new AjaxResult(HttpStatus.ERROR,"账号不存在");
        }

        //判断密码是否正确
        //加密用户输入的密码
//        String pwd = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        String pwd = loginDto.getPassword();
        if (!pwd.equals(user.getPassword())) return new AjaxResult(HttpStatus.ERROR,"账号或密码错误！");

        //判断账号状态
        if (user.getStatus() == 2) return new AjaxResult<>(HttpStatus.ERROR,"该账号已禁用，请联系管理员！");
        //将用户信息转换为map
        Map map = BeanUtil.beanToMap(user);
        //将密码移除
        map.remove("password");
        map.put("username",user.getUsername());
        String role = "";
        //处理角色
        switch (user.getSysType()) {
            case 1:
                role = RoleConstant.ADMIN;
                break;
            case 2:
                role = RoleConstant.MERCHANT;
                break;
            case 3:
                role = RoleConstant.PLATFORM;
                break;
        }
        List<String> roleList=new ArrayList<>();
        roleList.add(role);
        map.put("roles", roleList);
        //生成token
        String token = tokenTemplate.generateToken(map);
        map.put("accessToken", token);
        return new AjaxResult<>(HttpStatus.SUCCESS,"登录成功", map);
    }
}
